// modals
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

var ajaxText = ['.', '..', '...', '....', '.....']
var ajaxI = 0;
function showAjax() {
  $('#ajaxLoader p:eq(1)').html(ajaxText[ajaxI++%5]);
}

var notIE6 = true;
if ($.browser.msie && $.browser.version.substr(0,1)<7) {
    notIE6 = false;
}
var _settings = { mask: { color: '#000', loadSpeed: 400, opacity: 0.85 }, close: '.closeModal', closeOnClick: true, left: 'center', oneInstance: false, fixed: notIE6 };
$('a.modal').each(function(i){
    $('body').append('<div id="overlay'+i+'" class="animated fadeInDown"></div>');
    $('div#overlay'+i).hide();
    var toload = $(this).attr('href') + ' .genericmodal';
    $('div#overlay'+i).load(toload, function(){
        $(this).overlay(_settings);
    })
});
$('a.modal').click(function(e){
    var i = $('a.modal').index(this);
    $('div#overlay'+i).overlay().load();
    e.preventDefault()
});

$('a.closeModal').live('click', function(e){
    e.preventDefault()
})
// smooth scroll
$('a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname) {
		var $target = $(this.hash);
		$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
		if ($target.length) {
			var targetOffset = $target.offset().top;
			$('html,body').animate({scrollTop: targetOffset}, 2000);
			return false;
		}
    }
});

// add browser
if ($('#browser_instructions').length) {
var str1 = navigator.appVersion;
var str2 = "Mac";
var str3 = "Windows NT 5.1";
var className = "none";
if (str1.indexOf(str2) != -1) {
    className = 'mac';
} else if (str1.indexOf(str3) != -1) {
    className = 'xp';
}
$("#browser_instructions").addClass(className);
}

if ($('body.index2').length) { 
  $.cookie('countryCode', null);
  $.cookie('state', null);
  $.cookie('countryName', null);
  var countryCode = geoip_country_code();
  var countryName = geoip_country_name();
  var state = geoip_region_name();
  if (state === 'South Dakota') {
    var internalLink = true;
    window.location = './na.php'; 
  }
  $.cookie('countryCode', countryCode);
  $.cookie('state', state);
  $.cookie('countryName', countryName);


}

if ($('#id_countryName').length) {
    $('input[name=zip]').addClass('required');

    var countryCode = $.cookie('countryCode');
    var string = "Australia, Canada, New Zealand, United Kingdom, United States of America";
    var state = $.cookie('state');
    var countryName = $.cookie('countryName');

    function selectState(currentState) {
       $('#id_state option').filter(function() {
       return $(this).text() === currentState;  
    }).attr('selected',true);
    }

    if ($('input[name=dayPhoneIndex]').length) {
    var $dayPhone = $("input[name=dayPhoneIndex]");
    } else {
    var $dayPhone = $("input[name=dayPhone]");
    }

if ($('input[name=zip]').length) {
    $zipG = $("input[name=zip]");
}
  ($('#checkoutForm').length) ? $formName = $('#checkoutForm') : $formName = $('#checkoutForm2')

  function zipRemove() {
    $zipG.removeClass();
    $zipG.val('');
    $dayPhone.removeClass();
    $zipG.addClass('required');
    $formName.validate().element('input[name=zip]');
  }
  function zipAdd() {
    $zipG.removeClass();
    $dayPhone.addClass('required phone')
    $zipG.addClass('required zipcode');
    // $zipG.mask2("?99999");
    if($("input[name=zip]").attr("value") != "")
    	{
    		$formName.validate().element('input[name=zip]');
    	}
  }

  if ($('#id_state2').length) { $('#id_state2').hide() }
    function switchCountry(selectCountry){
      if (selectCountry === 'US') {
        $('#id_state').prop("disabled", false);
        $('#id_state').show();
        $('#id_state2').hide();
        $('#id_state2').prop("disabled", true);
      } else 
      // non - US
      {
        $('#id_state').prop("disabled", true);
        $('#id_state').hide();
        $('#id_state2').show();
        $('#id_state2').prop("disabled", false);
      }
           return false;
    }
    $('.phoneGeneric, .zipGeneric').live('keyup blur', function(){
        var myValue = $(this).val();
        $(this).val( myValue.replace(/[^a-zA-Z0-9+ -]/g,'') );
    });

   if (string.indexOf(countryName) != -1 && countryName != '') {
       $('#id_countryName').val(countryCode);
       switchCountry(countryCode);
       if (countryCode === 'US') {
           selectState(state);
           zipAdd();
       }
   } else {
      // $('#id_countryName').val('US');
      $('#id_countryName').val(countryCode);
      switchCountry(countryCode);
      // $dayPhone.addClass("phone");
   }

    $('#id_countryName').change(function() {
           var selectCountry = $(this).val();
           if (selectCountry ===  'US') {
               zipAdd();
               switchCountry(selectCountry);
               $formName.validate().element($dayPhone);
           } else {
               zipRemove();
               switchCountry(selectCountry);
               $formName.validate().element($dayPhone);
           }
        });
        if ($('#id_state').length) { 
          $('#id_state').change(function() {
           $formName.validate().element('#id_state');
          })
        }
        if ($('#id_fields_expmonth').length) { 
          $('#id_fields_expmonth').change(function() {
           $formName.validate().element('#id_fields_expmonth');
          })
        }
        if ($('#id_fields_expyear').length) { 
          $('#id_fields_expyear').change(function() {
           $formName.validate().element('#id_fields_expyear');
          })
        }
    }

if ($('body.searching').length) {
    var countryName = $.cookie('countryName');
    var city = $.cookie('state');
    var text = city + ', ' + countryName;
    $(".dynamic").text(text);
    $(".dynamic2").text(city);
}

if ($('#discount-bar').length) {
setInterval("$('#discount-bar p span').toggle();",500);
}

if ($('.arrowBarBg2, .arrowBarBg3, .arrowBarBg4,').length) {
setInterval("$('.arrowBarBg2 h1, .arrowBarBg3 h1, .arrowBarBg4 h1').toggle();",500);
}

if ($('body.upsell').length) {
var maskSettings = { color: '#000', loadSpeed: 0, opacity: 0.85 };
    $('#ajaxLoader').hide();
    $('.upgradebtn, .yesbtn').live('click', function(e) { 
        $('#ajaxLoader').overlay({ mask: maskSettings, closeOnClick: false, oneInstance: false, top: '30%', onLoad: function() { $('#frmUpgrade').submit(); setInterval("showAjax()",500) }});
        $('#ajaxLoader').overlay().load();
        $('#ajaxLoader').addClass('animated flipInX');
      });
    $('.noty').live('click', function(e) { 
        $('#ajaxLoader').overlay({ mask: maskSettings, closeOnClick: false, oneInstance: false, top: '30%', onLoad: function() { $('#frmNoThanks').submit(); setInterval("showAjax()",500) }});
        $('#ajaxLoader').overlay().load();
        $('#ajaxLoader').addClass('animated flipInX');
    });

}

if (window.MediaElement) {
  $('audio, video').mediaelementplayer({
    success: function(player, node) {
      $('#' + node.id + '-mode').html('mode: ' + player.pluginType);
    }
  }); 
}

if ($('input.applyc').length) { 
  $('input.applyc').click(function(e){
    e.preventDefault;
    if ($('input[name=code]').val().toUpperCase() == 'OFF20') {
          alert("Congratulations! Your discount has been applied.");
		  $('.inneR h5').html('$79.00');
          $('.prodDetBot .amt li span').html('$79.00');
		  $('#discount').html('$20.00');
		  $("#product_id").attr("value",'FAO79F1D');
        } else {
		  alert("We're sorry, your discount has not been applied. Please check your code and try again.");
		  $('.inneR h5').html('$99.00');
          $('.prodDetBot .amt li span').html('$99.00');
		  $('#discount').html('$0.00');
		  $("#product_id").attr("value",'FAO99F1D');
		}
    return false;
  })
}

// indexb form //

	$('#checkoutFormB input').focus(function(){
        if ( (this.value) == this.defaultValue )
          this.value = '';
    }).blur(function(){
        if ( (this.value) == '' )
            this.value = this.defaultValue;
    });
		var btn01 = $('#indexbform1 .btncontinue');
		var btn02 = $('#indexbform2 .btncontinue');
		var btn03 = $('#indexbform3 .btncontinue');
		var pos1 = {'left': 0, top: '0'}
		var pos2 = {'left': -920, 'top': 0}
		var pos3 = {'left': -2000, 'top': 0}
		var pos4 = {'left': 600, 'top': 0}
		var pos5 = {'left': 1000, 'top': 0}
		$('#indexbform1').css(pos1);
		$('#indexbform2').hide();
		$('#indexbform3').hide();
		$(btn01).live('click', function() {
			if ($('#checkoutFormB input[name=zip]').is('.valid')) {
        $('#indexbform2').fadeIn('slow').addClass('animated pulse');
        $('#indexbform1').animate(pos4, 800).fadeTo('fast', 0.5);
			}
		});
		$(btn02).live('click', function() {
			if ($('#checkoutFormB input[name=email]').is('.valid')) {
        $('#indexbform3').fadeIn('slow').addClass('animated pulse');
        $('#indexbform2').animate(pos4, 1000).fadeTo('fast', 0.5);
        $('#indexbform1').animate(pos5, 800).fadeTo('fast', 0.5);
			}
		});

$(function (){  
  
if (window.jQuery.fn.idleTimer) {
  
  var timeout = 1500000;

  $(document).bind("idle.idleTimer", function(){
    alert("Are you still there? We want to make sure you don't miss out on today's limited time offer!")
  });

  $.idleTimer(timeout);

}

});  
